/* Copyright (C) Abu Rizal, 2009.
 * 
 * This file is part of QurText.
 * 
 * QurText is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * QurText is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with QurText. If not, see <http://www.gnu.org/licenses/>.
 */
package qurtext.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import qurtext.factory.MediaFactory;

@SuppressWarnings("serial")
public class MediaServlet extends HttpServlet {

	private MediaFactory mediaFactory=new MediaFactory();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		String filename=req.getPathInfo().substring(1);
		String source="http://www.versebyversequran.com/data/Menshawi_16kbps/";
		ServletOutputStream stream=response.getOutputStream();
		try {
		      byte[] mp3 = mediaFactory.getMediaContent(source, filename, false, "Menshawi_16kbps/"+filename);

		      //set response headers
		      response.setContentType("audio/mpeg");

		      response.addHeader("Content-Disposition", "attachment; filename="
		          + filename);

			response.setContentLength((int) mp3.length);

		        stream.write(mp3);
		    } catch (IOException ioe) {
		      throw new ServletException(ioe.getMessage());
		    } finally {
		      if (stream != null)
		        stream.close();
		    }	
	}
}
